package com.lxz.jucdemo.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: 刘新智
 * @Date: 2025/10/27 14:41
 * @Description: Condition精准唤醒线程
 * @Version: v1.0
 */
public class ProductConsumeTest3 {
    public static void main(String[] args) {
        Data3 data = new Data3();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.printA();
            }
        }).start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.printB();
            }
        }).start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.printC();
            }
        }).start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.printD();
            }
        }).start();
    }
}

class Data3{

    private int number=0;

    Lock lock=new ReentrantLock();
    Condition conditionA=lock.newCondition();
    Condition conditionB=lock.newCondition();
    Condition conditionC=lock.newCondition();
    Condition conditionD=lock.newCondition();

    public  void printA(){
        lock.lock();
        try {
            while (number!=0){
                conditionA.await();// A等待
            }
            number++;
            System.out.println(Thread.currentThread().getName()+":AAAAAAAAAAAA");
            conditionB.signal();// 唤醒B
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public  void printB(){
        lock.lock();
        try {
            while (number!=1){
                conditionB.await();// B等待
            }
            number++;
            System.out.println(Thread.currentThread().getName()+":BBBBBBBBBB");
            conditionC.signal();// 唤醒C
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public  void printC(){
        lock.lock();
        try {
            while (number!=2){
                conditionC.await();// C等待
            }
            number++;
            System.out.println(Thread.currentThread().getName()+":CCCCCCCCCCC");
            conditionD.signal();// 唤醒D
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public  void printD(){
        lock.lock();
        try {
            while (number!=3){
                conditionD.await();// D等待
            }
            number=0;
            System.out.println(Thread.currentThread().getName()+":DDDDDDDDDDDDD");
            conditionA.signal();// 唤醒A
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}


